<?php
    date_default_timezone_set('Europe/Kiev');
    global $current_user;
    get_currentuserinfo();
    $date = date('H:i:s d:m:Y');
    if (isset($_POST['submit']))
    {
        $title = $_POST['title'];
        $decr = $_POST['decr'];
        $cust_name = $_POST['cust_name'];
        $cust_mail = $_POST['cust_mail'];
        $performer = $_POST['performer'];
        $user_query = "SELECT ID, user_email FROM crm_users WHERE display_name='".$performer."'";
        $user_result = mysql_query($user_query);
        while ($row = mysql_fetch_array($user_result))
        {
            $performer_mail = $row['user_email'];
            $performer_id = $row['ID'];
            $query = "INSERT INTO crm_orders (title, descr, customer, customer_mail, performer, performer_mail, performer_id, updated_by, updated) VALUES
                    ('".$title."', '".$decr."', '".$cust_name."', '".$cust_mail."', '".$performer."', '".$performer_mail."', '".$performer_id."', '".$current_user->user_login."', '".$date."')";
            $result = mysql_query($query);
            $user_query2 = "UPDATE crm_users SET user_orders=`user_orders` + 1 WHERE ID='".$performer_id."'";
            $result2 = mysql_query($user_query2);
            if ($result)
            {
                echo "Запись успешно добавлена в базу данных.\n";
            }
        }
        echo '<br/><input type="button" onclick="history.back();" value="Назад"/><br/>';
    }
    else
    {
        echo '<form method="post" name="form" action="">';
        echo '<label>Введите тему: </label>';
        echo '<input name="title" style="width: 100%" type="text"></input>';
        echo '<br>';
        echo '<label>Введите текст и описание задачи: </label>';
        echo '<input name="decr" style="width: 100%" type="text"></input>';
        echo '<br>';
        echo '<label>Введите ФИО заказчика: </label>';
        echo '<input name="cust_name" style="width: 100%" type="text"></input>';
        echo '<br>';
        echo '<label>Введите E-Mail заказчика: </label>';
        echo '<input name="cust_mail" style="width: 100%" type="text"></input>';
        echo '<br>';
        echo '<label>Выберите исполнителя:</label>';
        echo '<form method="post">
          <select name="performer">
          <option value="">Выберите исполнителя: </option>';
        $result =  mysql_query("SELECT id, display_name FROM crm_users ORDER BY id")
            or die ("<b>Query failed:</b> " . mysql_error());
        while ($row = mysql_fetch_array($result))
        {
            echo "<option value='".$row['display_name']."'>".$row['display_name']."</option>";
        }
        echo '</select>';
        echo '<br>';
        echo '<input name="submit" type="submit" value="Создать задачу"></input>';
        echo '</form>';
        echo '<input type="button" onclick="history.back();" value="Назад"/><br/>';
    }
?>